<template>
  <div class="login-page">
    <validateForm @form-submit="onFromSubmit">
      <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label"
          >邮箱地址</label
        >
        <ValidateInpt
          :rules="emailRules"
          v-model="emailVal"
          @value="emailValue"
          placeholder="请输入正确的电子邮箱地址"
        >
        </ValidateInpt>
      </div>
      <div class="mb-3">
        <label for="exampleFormControlTextarea1" class="form-label">密码</label>
        <ValidateInpt
          :rules="passwordRules"
          v-model="passwordVal"
          @value="passwordValue"
          placeholder="请输入正确的密码"
        >
        </ValidateInpt>
      </div>
      <template #submit>
        <button class="btn btn-danger">登录</button>
      </template>
    </validateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import validateForm from "@/components/validateForm.vue";
import ValidateInpt, { RulesProp } from "@/components/ValidateInpt.vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import createMessage from "@/hooks/createMessage";

export default defineComponent({
  name: "LoginIndex",
  components: {
    validateForm,
    ValidateInpt,
  },

  setup() {
    const emailVal = ref("111@test.com");
    const emailRules: RulesProp = [
      //这个是邮箱的规则，应该被这个东西约束
      {
        type: "required",
        message: "电子邮箱地址不能为空",
      },
      {
        type: "email",
        message: "请输入正确的电子邮箱",
      },
    ];
    const passwordVal = ref("111111");

    const passwordRules: RulesProp = [
      {
        type: "required",
        message: "密码不能为空",
      },
    ];

    const emailValue = (val: string) => {
      emailVal.value = val;
      // console.log(val);
    };
    const passwordValue = (val: string) => {
      passwordVal.value = val;
    };
    const store = useStore();
    const router = useRouter();
    const onFromSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value,
        };
        store.dispatch("loginAndFecth", payload).then(() => {
          createMessage("登录成功2秒后跳转", "success", 2000);
          setTimeout(() => {
            router.push("/");
          }, 2000);
        });
      }
    };
    return {
      emailRules,
      emailVal,
      emailValue,
      onFromSubmit,
      passwordVal,
      passwordRules,
      passwordValue,
    };
  },
});
</script>

<style scoped></style>
